<?php

namespace backend\controllers;

use common\models\Contact;
use Yii;

class ContactController extends DashboardController
{
    # 加载页面
    public function actionIndex()
    {
        $contact = Contact::find()->asArray()->one();
        $data = empty($contact) ? [] : $contact;

        return $this->render('index',compact('data'));
    }

    # 保存数据
    public function actionSave()
    {
        $post = Yii::$app->request->post();

        $contactObj = empty($post['id']) ? new Contact() : Contact::find()->where(['id' => $post['id']])->one();

        $saveData = [
            'name' => empty($post['name']) ? '' : $post['name'],
            'desc' => empty($post['desc']) ? '' : $post['desc'],
            'address' => empty($post['address']) ? '' : $post['address'],
            'qq' => empty($post['qq']) ? '' : $post['qq'],
            'wechat' => empty($post['wechat']) ? '' : $post['wechat'],
            'mail' => empty($post['mail']) ? '' : $post['mail'],
            'tel' => empty($post['tel']) ? '' : $post['tel']
        ];

        $contactObj->attributes = $saveData;

        if ($contactObj->validate()){
            $msg = $contactObj->save() ? ["state" =>"success","message" =>"恭喜小主，操作成功！"] : ["state" => "error","message" => "小主大人，操作失败啦！"];
            $this->ajaxReturn($msg);
        }else {
            $this->ajaxReturn(["state" => 'error', "message" => '验证失败']);
        }
    }
}